<?php
class GroupController extends Zend_Controller_Action 
{
    function init()
    {
        $this->initView();
        Zend_Loader::loadClass('AuxDbTable');
        Zend_Loader::loadClass('User');
        Zend_Loader::loadClass('Group');
        Zend_Loader::loadClass('Authgroup');
        Zend_Loader::loadClass('Mainmenu');
        Zend_Loader::loadClass('Rights');
        Zend_Loader::loadClass('Authority'); 
        $this->view->baseUrl = $this->_request->getBaseUrl();
        $this->view->user = Zend_Auth::getInstance()->getIdentity();
        $user = new User();
        $this->view->assigned_tos = $user->fetchAll('authgroup_id=2','last_name');
    }
    
    function preDispatch()
    {
        $auth = Zend_Auth::getInstance();
        if (!$auth->hasIdentity()) {
            $this->_redirect('auth/login');
        }
        $menu = new Mainmenu();
        $this->view->main_menu = $menu->getMenu($this->view->user->id);
    }

    function indexAction()
    {
        $Rights = new Rights();
        if(!$Rights->CanDo($this->view->user->id,'group','index')) $this->_redirect(DEFAUL_URL);
        
        $this->view->title = "Groups";
        $this->view->content_title = "Groups";
        $group = new Group();
        $this->view->items = $group->fetchAll('deleted!=1');
        
        $teacher = new User();
        foreach($this->view->items as $item) {
            $item->assigned_to = $teacher->getUser($item->assigned_to);
        }
        
        $this->view->can_add = $Rights->CanDo($this->view->user->id,'group','add');
        $this->view->can_edit = $Rights->CanDo($this->view->user->id,'group','edit');
        $this->view->can_delete = $Rights->CanDo($this->view->user->id,'group','delete');
        
        $this->render();
    }
    
    function validate($id,$params)
    {
        $valid = true;
        $obj = new Group();
        
        if(strlen($params['name'])==0)
        {
            $this->view->message .= 'Please, enter Name.<br>';
            $valid = false;
        }    
                
        
        //email
        $email_pattern = '/^[A-Z0-9\._\-]+@[A-Z0-9\.\-]+\.[A-Z]{2,6}$/i';
        
        //date 
        $date_pattern = '/^[0-9]{4}\-(?:0[1-9]|1[0-2])\-(?:[0-2]?[0-9]|3[0-1])$/';
        if(!preg_match($date_pattern,$params['start_date']))
        {
            $this->view->message .= 'Invalid Start date '.$params['start_date'].'. Format yyyy-mm-dd.<br>';
            $valid = false;
        } 
        if($params['end_date'] && !preg_match($date_pattern,$params['end_date']))
        {
            $this->view->message .= 'Invalid End date '.$params['end_date'].'. Format yyyy-mm-dd.<br>';
            $valid = false;
        } 
        //time
        $time_pattern = '^(([0-9])|([0-1][0-9])|([2][0-3])):(([0-9])|([0-5][0-9]))$';
                
        return $valid;
    }
    function addAction()
    {
        $Rights = new Rights();
        if(!$Rights->CanDo($this->view->user->id,'group','add')) $this->_redirect(DEFAUL_URL);
        
        $this->view->content_title = $this->view->title = "Add New Group";
        $params = array();

        if (strtolower($_SERVER['REQUEST_METHOD']) == 'post') {
            Zend_Loader::loadClass('Zend_Filter_StripTags');
            $filter = new Zend_Filter_StripTags();
            
            $params['name'] = trim($filter->filter($this->_request->getPost('name')));
            $params['assigned_to'] = trim($filter->filter($this->_request->getPost('assigned_to')));
            $params['start_date'] = trim($filter->filter($this->_request->getPost('start_date')));
            if(trim($filter->filter($this->_request->getPost('end_date')))) $params['end_date'] = trim($filter->filter($this->_request->getPost('end_date')));
                    
            $this->view->message = '';
            if($this->validate(0,$params)) {
                $obj = new Group();
                $new_id = $obj->insert($params);
                
                $this->_redirect('/group');
                return;
            }
        } 
        
        // set up an "empty" studygroup        
        $this->view->item = new stdClass();
        $this->view->item->id = null;
        $this->view->item->name = isset($params['name'])?$params['name']:'';
        $this->view->item->assigned_to = isset($params['assigned_to'])?$params['assigned_to']:'';
        $this->view->item->start_date = isset($params['start_date'])?$params['start_date']:date('Y-m-d');
        $this->view->item->end_date = isset($params['end_date'])?$params['end_date']:'';
                        
                    
        // additional view fields required by form
        $this->view->action = 'add';
        $this->render();
    }
    
    function editAction()
    {
        $Rights = new Rights();
        if(!$Rights->CanDo($this->view->user->id,'group','edit')) $this->_redirect(DEFAUL_URL);
            
        $this->view->content_title = $this->view->title = "Edit Group";
        $obj = new Group();
        
        if (strtolower($_SERVER['REQUEST_METHOD']) == 'post') {
            Zend_Loader::loadClass('Zend_Filter_StripTags');
            $filter = new Zend_Filter_StripTags();
            
            $id = (int)$this->_request->getPost('id');
            $params = array();
            $params['name'] = trim($filter->filter($this->_request->getPost('name')));
            $params['assigned_to'] = trim($filter->filter($this->_request->getPost('assigned_to')));
            $params['start_date'] = trim($filter->filter($this->_request->getPost('start_date')));
            if(trim($filter->filter($this->_request->getPost('end_date')))) $params['end_date'] = trim($filter->filter($this->_request->getPost('end_date')));
                        
            if ($id !== false) {
                $this->view->message = '';
                if($this->validate($id,$params)) {
                    $where = 'id = ' . $id;
                    $obj->update($params, $where);
                
                    $this->_redirect('/group');
                    return;
                } else {
                    $this->view->item = $obj->fetchRow('id='.$id);
                    $this->view->item->id = $id;
                    
                    if( $params['name']) $this->view->item->name = $params['name'];
                    if( $params['assigned_to']) $this->view->item->assigned_to = $params['assigned_to'];
                    if( $params['start_date']) $this->view->item->start_date = $params['start_date'];
                    if( $params['end_date']) $this->view->item->end_date = $params['end_date'];
                                    
                }
            }
        } else {
            $id = (int)$this->_request->getParam('id', 0);
            if ($id > 0) {
                $this->view->item = $obj->fetchRow('id='.$id);
            }
        }

        // additional view fields required by form
        $this->view->action = 'edit';
        
        $this->render();
    }
    
    function deleteAction()
    {
        $Rights = new Rights();
        if(!$Rights->CanDo($this->view->user->id,'group','delete')) $this->_redirect(DEFAUL_URL);
        
        $this->view->content_title = $this->view->title = "Delete Group";
        
        $obj = new Group();
        if (strtolower($_SERVER['REQUEST_METHOD']) == 'post') {
            Zend_Loader::loadClass('Zend_Filter_Alpha');
            $filter = new Zend_Filter_Alpha();
            
            $id = (int)$this->_request->getPost('id');
            $del = $filter->filter($this->_request->getPost('del'));
            
            if ($del == 'Yes' && $id > 0) {
                $data = array(
                        'deleted' => '1'
                );
                $where = 'id = ' . $id;
                $obj->update($data, $where);
            }
        } else {
            $id = (int)$this->_request->getParam('id');
            if ($id > 0) {
                // only render if we have an id and can find the studygroup.
                $this->view->item = $obj->fetchRow('id='.$id);
                
                if ($this->view->item->id > 0) {
                    $this->render();
                    return;
                }
            }
        }
        
        // redirect back to the project list unless we have rendered the view
        $this->_redirect('/group');
    }
    
}